<?php
/**
 *@author sparkguo 
 *@date 2017-09-22   沃尔玛订单抓取与交运回传
 */
defined('BASEPATH') OR exit('No direct script access allowed');
ini_set('max_execution_time', '0');
class WalmartShop extends CI_Controller {
    
    public $WalmartURL='';
    public $Timestamp='';
    
	function __construct(){
		parent::__construct();
        $this->Timestamp =round(microtime(true)*1000); //Current system timestamp
		$this->load->model('Function_m','fun');
        $this->load->model('Report_m','m');
		$this->pageSize =$this->config->item('pagenum');
    }  
    function getxmldata1(){
        $site_root=$_SERVER['DOCUMENT_ROOT'];
        $file_path=$site_root."/amazonOrder.xml";
        $reader=new XMLReader();
        //$reader->open($file_path);
        /*while ($reader->read()){
            //这里放循环解析的条件~
            
        }*/
        $retdata=$this->parseXmlFile($file_path);
        dump($retdata);
    }
    
    public function diffSalesCount(){
    	$starttime =$getstarttime= $this->input->get('starttime');	//开始时间
    	$endtime   = $this->input->get('endtime');		//结束时间
        $starttime=$starttime==''?date("Y-m-d",strtotime('-1 month')+86400):$starttime;
        $endtime=$endtime==''?date("Y-m-d"):$endtime;
    	//查询开始与结束时间每天的日收入
    	$shopname	   = $this->input->get('shopname');
        $shopname=trim($shopname,',');
        $can_visit_shop=$this->getViewShops();
        if($can_visit_shop!='isadmin' && $shopname==''){
            if(!empty($getstarttime)){
                $shopname=$can_visit_shop;
            }
        }
        
        $tpl_data=array('starttime'=>$starttime,'endtime'=>$endtime,'shopname'=>$shopname);
    	if (strlen($shopname) >0){
    	    $shopname=explode(',',$shopname);
    		$whereshop = implode("','",$shopname);
            $mb_where=" AND SELL.SHOPTYPE IN ( '$whereshop')";
    	}else{
            if($_COOKIE["department"] ==1 || $_COOKIE["power"]=='all' || $_COOKIE["department"]=='5'){//管理者能看到所有店铺
            	
            }else{
                if(!empty($getstarttime)){
                    die("请先选择您要统计的店铺， <a href='javascript:history.back()'>【返回】</a>");
                }
            }
    	}
        $this->db2 = $this->load->database('oracle', TRUE);
        $last_starttime=date('Y-m-d',strtotime("-1 year",strtotime($starttime)));
        $last_endtime=date('Y-m-d 23:59:59',strtotime("-1 year",strtotime($endtime)));//wmsys.wm_concat(SELL.SHOPTYPE) as shopname,
       
        //dump($mabangsells);
        if($whereshop)$wherestr=" AND shopname in('".$whereshop."')";
        if(!empty($getstarttime)){
         $sql = "SELECT 
            SUM(sell.ordernum) AS ordernum,SELL.SHOPTYPE,
            SUM(sell.intotal) AS intotal,
            SUM(sell.inexpress) AS inexpress,
            SUM(sell.intotal + sell.inexpress) AS inall,
            SUM(sell.outtotal) AS outtotal,
            SUM(sell.outexpress) AS outexpress,
            SUM(sell.outebayfee) AS outebayfee,
            SUM(sell.outpaypalfee) AS outpaypalfee,
            SUM(sell.OUTPACKAGINGFEE) AS OUTPACKAGINGFEE,
            SUM(sell.outtotal + sell.outexpress + sell.outebayfee + sell.outpaypalfee + sell.OUTPACKAGINGFEE) AS outall
        FROM db_selltostat sell
            LEFT JOIN db_product product ON sell.productid = product.sid
        WHERE 1 = 1 $mb_where
            AND sell.ORDERTIME >= to_date('$last_starttime', 'yyyy-MM-dd') AND sell.ORDERTIME <= to_date('$last_endtime', 'yyyy-MM-dd HH24:mi:ss')
        GROUP BY SELL.SHOPTYPE";//to_char(sell.ordertime, 'yyyymmdd'),to_date(to_char(sell.ordertime, 'yyyymmdd'), 'yyyy-mm-dd') AS yyyymmdd,
            $res = $this->db2->query($sql);
            $mabangorders = $res->result();
            $mabangsells=$new_shops=array();
            $totalinfo=array();
            foreach($mabangorders as $key=>$val){
                $val=object_array($val);
                $val['INALL']=round($val['INALL'],2);
                $mabangsells[$val['SHOPTYPE']]=$val;
                $totalinfo['mb_ordernum']+=$val['ORDERNUM'];
                $totalinfo['mb_total']+=$val['INALL'];
            }
            $mb_shops=iarray_column($mabangorders,'SHOPTYPE');
            
            //查询开始与结束时间每天的日收入
            $orders=$this->m->getOrderAmountList($starttime,$wherestr,$endtime,"shopname","order_num");
            $daysales=array();
            foreach($orders as $key=>$val){
                $subtotal = $val['goods_amount_total'] +$val['shipping_fee_total'];
                $subzhic = $val['costprice_total']+$freight+$val['realexpress_fre']+ $val['payfee_total']+ $val['platform_fee_total'];
                $lirun = $subtotal - $subzhic;
        		if($subtotal){
        			$maoliv = round(($lirun/$subtotal)*100,2);
        		}else{
        			$maoliv=0;
        		}    
                $res=array("orderAmount"=>$val['goods_amount_total'],"shipping_fee"=>$val['shipping_fee_total'],"subtotal"=>round($subtotal,2),
                "cosprice"=>$val['costprice_total'],"freight"=>$val['realexpress_fre'],'shopname'=>$val['shopname']
                ,"platformfee"=>$val['platform_fee_total'],"payfee"=>$val['payfee_total'],'orderDate'=>$val['dates'],
                "subzhic"=>number_format($subzhic,2),"goodsnNum"=>$val['sell_total'],
                'diff_money'=>round($subtotal-$mabangsells[$val['shopname']]['INALL'],2),
                "orderNum"=>$val['order_num'],"lirun"=>number_format($lirun,2),"maoliv"=>$maoliv."%");
                
                $daysales[]=$res;    
          		$totalinfo['ordernum']+=$val['order_num'];
                $totalinfo['total']+=$subtotal;
            }
            $shopsame_list=iarray_column($daysales,'shopname');
            $un_show_shop=$un_show_shopnames=array();
        
            foreach($mabangsells as $key=>$val){
                if(!in_array($val['SHOPTYPE'],$shopsame_list)){
                    $un_show_shop[]=$val;
                    $saleinfo=array('shopname'=>$val['SHOPTYPE'],
                    'mb_orderNum'=>$val['ORDERNUM'],'mb_subtotal'=>$val['INALL'],'diff_money'=>-$val['INALL']);
                    $daysales[]=$saleinfo;
                    $un_show_shopnames[]=$val['SHOPTYPE'];
                }                 
            }
            if(count($un_show_shopnames)>0)$where=" and name in ('".implode("','",$un_show_shopnames)."')";
            $delshops = $this->fun->getdatabaseslist("d_shop","$where","id,name,platfromname,del_flag,updateoper,otherUpload");
            foreach($delshops as $key=>$val){
                $delshops[$val['name']]=$val;
            }
            $daysales=sort_list($daysales,'diff_money','asc');
            
            $totalinfo['diff_money']=$totalinfo['total']-$totalinfo['mb_total'];
            $totalinfo['mb_total']=number_format($totalinfo['mb_total'],2);
            $totalinfo['total']=number_format($totalinfo['total'],2);
            $un_show_shop=sort_list($un_show_shop,'INALL');
            $tpl_data['delshops']=$delshops;
            $tpl_data['totalinfo']=$totalinfo;
            $tpl_data['un_show_shop']=$un_show_shop;
            $tpl_data['mabangsells']=$mabangsells;
            $tpl_data['list']=$daysales;
             $tpl_data['newshops']=$new_shops;
            //dump($daysales);
            if($allsubtotal)
            		$allmaolv = round(($alllirun / $allsubtotal)*100,2);
            
        	$this->tpl->assign("allorderAmount", number_format($allorderAmount,2));
        	$this->tpl->assign("allshipping_fee", number_format($allshipping_fee,2));
        	$this->tpl->assign("allsubtotal", number_format($allsubtotal,2));
        	$this->tpl->assign("allcosprice", number_format($allcosprice,2));
        	$this->tpl->assign("allnum", $allnum);
        	$this->tpl->assign("allorderNum", $allorderNum);
        	$this->tpl->assign("allfreight", number_format($allfreight,2));
        	$this->tpl->assign("allpayfee", number_format($allpayfee,2));
        	$this->tpl->assign("allsubzhic", number_format($allsubzhic,2));
        	$this->tpl->assign("alllirun", number_format($alllirun,2));
        	$this->tpl->assign("allmaolv", $allmaolv."%");
        	$this->tpl->assign("allplatformfee", number_format($allplatformfee,2));
        }
        $this->tpl->assign($tpl_data);

        $this->tpl->display("WalmartShop/test.tpl");  
    }
    
    /**
     * 解析返回的XML文档
     */
    public function parseXmlFile($xmlFile){
        $reader = new \XMLReader();
        $reader->open($xmlFile, 'UTF-8');
        $nodeName = '';
        $dataList = array();
        $data = array();
        while ($reader->read()){
            if($reader->nodeType == \XMLReader::ELEMENT){
                $nodeName = $reader->name;
                if($nodeName=='MerchantFulfillmentID'){
                    if($reader->value!='AFN'){
                        break;
                    }
                }else{
                    if($nodeName=='person'){
                        $data = array(
                            'username'=>$reader->getAttribute('username'),
                            'age'=>$reader->getAttribute('age'),
                        );
                    }
                }
            }
            if($reader->nodeType == \XMLReader::TEXT && !empty($nodeName)){
                if($nodeName=='person'){
                    $data['description'] = strtolower($reader->value);
                    $dataList[] = $data;
                }
            }
        }
        $reader->close();
        return $dataList;
    }


 
    function getXmlData(){
        $site_root=$_SERVER['DOCUMENT_ROOT'];
        $xml_data=file_get_contents($site_root."/amazonOrder.xml");
        //dump($xml_data);
        $objectxml = simplexml_load_string($xml_data);//将文件转换成 对象  
        $xmljson= json_encode($objectxml );//将对象转换个JSON  
        $xmlarray=json_decode($xmljson,true);//将json转换成数组 
        $orders_arr=$xmlarray['Message']['SettlementReport'];
        
        $total_price=$total_pay=0;
        if(isset($xmlarray['Message']['SettlementReport']['SettlementData'])){
            echo 'inhere';
            $orders_arr=array();
            $orders_arr[0]=$xmlarray['Message']['SettlementReport'];
        }
        //dump($orders_arr);
        foreach($orders_arr as $i=>$order_group){
            $orderdata=$order_group['Order'];    
            foreach($orderdata as $key=>$rs){
                $income_price=$pay_price=0;
                $price_arr=$rs['Fulfillment']['Item'];
                if($rs['Fulfillment']['MerchantFulfillmentID']!='AFN'){
                    unset($orderdata[$key]);
                    continue;
                }
                if(isset($price_arr[0]['AmazonOrderItemCode'])){
                    foreach($price_arr as $index=>$iteminfo){
                        $income_price=$pay_price=0;
                        if(isset($iteminfo['ItemPrice']['Component']['Amount'])){
                            $income_price=$iteminfo['ItemPrice']['Component']['Amount'];    
                        }else{
                            foreach($iteminfo['ItemPrice']['Component'] as $index=>$priceinfo){
                                $income_price+=$priceinfo['Amount'];
                            }
                        }
                        if(isset($iteminfo['ItemFees']['Fee']['Amount'])){
                            $pay_price=$iteminfo['ItemFees']['Fee']['Amount'];    
                        }else{
                            foreach($iteminfo['ItemFees']['Fee'] as $index=>$payinfo){
                                $pay_price+=$payinfo['Amount'];
                            }
                        }
                        echo $key."&nbsp;".$income_price."&nbsp;".$pay_price."<br />";
                        $total_price+=$income_price;
                        $total_pay+=$pay_price; 
                    }                        
                }else{
                    if(isset($rs['Fulfillment']['Item']['ItemPrice']['Component']['Amount'])){
                        $income_price=$rs['Fulfillment']['Item']['ItemPrice']['Component']['Amount'];    
                    }else{
                        foreach($rs['Fulfillment']['Item']['ItemPrice']['Component'] as $index=>$priceinfo){
                            $income_price+=$priceinfo['Amount'];
                        }
                    }
                    if(isset($rs['Fulfillment']['Item']['ItemFees']['Fee']['Amount'])){
                        $pay_price=$rs['Fulfillment']['Item']['ItemFees']['Fee']['Amount'];    
                    }else{
                        foreach($rs['Fulfillment']['Item']['ItemFees']['Fee'] as $index=>$payinfo){
                            $pay_price+=$payinfo['Amount'];
                        }
                    }
                    echo $key."&nbsp;".$income_price."&nbsp;".$pay_price."<br />";
                    $total_price+=$income_price;
                    $total_pay+=$pay_price;  
                }
            }
        } 
        dump($total_price);
        dump($total_pay);
        echo "<table><tr><td>$total_price</td><td>$total_pay</td></tr></table>";
       // dump($xmlarray);
    }
 
       
    
    public function getViewShops(){
        $authname=$_COOKIE['username'];
        if($_COOKIE["department"] ==1 || $_COOKIE["power"]=='all' || $_COOKIE["department"]=='5'){//管理者能看到所有店铺
			$where = "";
            return 'isadmin';
		}else{
		    $viewsshops=array();
            $viewshopname = $_COOKIE["shopname"];	//开通了权限的人员需要绑定店铺
			if($viewshopname){
				$viewshopname = unserialize($viewshopname);
				if($viewshopname){
					foreach($viewshopname as $key=>$name){
                        $viewsshops[]=$name;
					}
				}
			}
            
            $this->load->model('Datareport_m','d');
            $where=" and (updateoper='".$authname."' or otherUpload like '%$authname%')";
            $shopname  = $this->d->selectShop($where);
            
            if(count($shopname)>0){
                foreach($shopname as $key=>$platlist){
                    foreach($platlist as $index=>$val){
                        $val['otherUpload']=explode(',',$val['otherUpload']);
                        if($val['updateoper']!=$authname and !in_array($authname,$val['otherUpload'])){
                            unset($shopname[$key][$index]);
                        }else{
                            $viewsshops[]=$val['name'];
                        }
                    }
                }
                
            }
            $viewshop=implode(",",$viewsshops);
            return $viewshop;
		}
    }
    
    public function index(){
        $Timestamp=$this->_getMicroTime();
        $url="https://developer.walmart.com/orderProxy/order-api-doc-app/rest/v3/orders?limit=10";
        $WalmartConsumerID ="e1f94fe9-5e9c-490f-b077-e1ec6fff9c8b"; 
        $Signaturedata=$this->_GetWalmartAuthSignature($url,"GET",$Timestamp); 
        $headers_info=array('ConsumerID'=>$WalmartConsumerID,'TIMESTAMP'=>$Timestamp,'SIGNATURE'=>$Signaturedata);
        echo date("Y-m-d H:i:s",$Timestamp/1000);
        //dump($headers_info);
        $api_call_and_args="limit=20";
        $resultxml=$this->apiCall($api_call_and_args,$headers_info,$url);
        dump($resultxml);
    }
    
    
    function _GetWalmartAuthSignature($URL, $RequestMethod, $Timestamp) {
        $WalmartPrivateKey ="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALc5ux5f6iYepuothKHrLzIP3qIHf0EuGmKHX9ScWRCxQXfdI1Rp48v8+Gngxqfs1CgI3PM1l10hHx7QWtrhlYkE9ChMQny4+rAv5megFO3wPwc3r0809cQqPmHhaEqXVCf1vuu2WyROYhmsQU4kFv5McZmau2/iCQ3WLstpQnHXAgMBAAECgYEAsoox2N5TtsOFmIm0RWd7/MdUBQVTLjtzgHEzo2SasVZYWimFRLtOOzcNBXb/fSCcd0pzqxacoSYmQgt7jO/mmhAkaTLb4LR/UCwGMQb5S8pWBrONqATO/qN+kvZfDTKOAN8xMF/Djx3XTVr4cSCnEUvP+6t7gw4U8UCCAODHgPECQQDkkEwpdoGxWU1g19lr6aHuFlYXppr1BWAiV117B/we3eoudMQaGA+36BryhbngMInMV59p68HKYHo54dlL6fk/AkEAzTg0J20yS9zO8DUYUKlmVMFMl6wjAzDnsum4orUJSS6xNVk0hMRr++g70S4zIDnYKlN45V/rTpb+OnJwCXgJaQJBAMTB116mLrVeO/dPOVLlV8mentRTTvf4fa5yaP29fPORc8Q0LpCMABQAEhqOtdlhz24CTDAhjLzL2swzOR1ZuH8CQBDUvjpJk2lzZ6l9wUvESPdEj0KVRJ3bYfVjg9gcXvGYmcIVWeBVt8GGT3mdf2XyOI9oHy84ybS9X4ZtolC0fpkCQArVp2q4GftzCnZA/oQU5fTxSQeeMV4ggSMDyTVsyWKtx2jlZYm+wcE51svDz1b8YtEx5Dde+vQOznoEOH5Y06Y=";//Your Walmart Private Key;
        $WalmartConsumerID ="e1f94fe9-5e9c-490f-b077-e1ec6fff9c8b"; 
        // CONSTRUCT THE AUTH DATA WE WANT TO SIGN
        $AuthData = $WalmartConsumerID."\n";
        $AuthData .= $URL."\n";
        $AuthData .= $RequestMethod."\n";
        $AuthData .= $Timestamp."\n";
        //echo $AuthData;
        // GET AN OPENSSL USABLE PRIVATE KEY FROMM THE WARMART SUPPLIED SECRET
        $Pem = $this->_ConvertPkcs8ToPem(base64_decode($WalmartPrivateKey));
        $PrivateKey = openssl_pkey_get_private($Pem);
        // SIGN THE DATA. USE sha256 HASH
        $Hash = defined("OPENSSL_ALGO_SHA256") ? OPENSSL_ALGO_SHA256 : "sha256";
        if (openssl_sign($AuthData, $Signature, $PrivateKey, $Hash)){ // IF ERROR RETURN NULL return null; }
            //ENCODE THE SIGNATURE AND RETURN
            //echo 'in here';
            return base64_encode($Signature);
        }
    }
    
    private function _getMicroTime(){
        list($t1, $t2) = explode(' ', microtime());
        $time=(float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
        $time=$time-28800000;
        return $time;
    }



    
    function sendHttpRequest($url, $headers, $post_fields) {
        $args = array();
        $connection = curl_init($url);            
        $curl_options = array(CURLOPT_HTTPHEADER=>$headers, CURLOPT_POSTFIELDS=>$post_fields,
        //CURLOPT_SSLVERSION=>CURL_SSLVERSION_TLSv1, CURLOPT_SSL_CIPHER_LIST =>"TLSv1",
        CURLOPT_SSL_VERIFYPEER=>false,
        CURLOPT_POST=>1, CURLOPT_RETURNTRANSFER=>1);  # data will be returned as a string
        curl_setopt_array($connection, $curl_options);
        $json_response = curl_exec($connection);
        if (curl_errno($connection) > 0) {
          echo curl_error($connection) . "\n";
          exit(2);
        }
        curl_close($connection);
        return $json_response;
    }
    
    function send_request($headers,$body,$url){
	   
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');  
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if(strpos($url,"ttps")>0){
    		//禁用后curl将终止服务端进行验证
    		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
    		//检查服务器ssl证书中是否存在一个公用名
    		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
        }
        //当需要通过curl_getinfo来获取发出请求的header信息时，该选项需要设置为true
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);   
		curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_POST, 0);
		$response= curl_exec($ch);
        $request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);//请求头
        dump($request_header);
        print_r($response);
        return $response;
	}
    
}
